import { Table} from "antd";
import { formatMessage } from '@/utils/i18n-transform';
import {useCallback, useEffect, useState} from "react";
import {
	AsyncPageSelect,
	AsyncPageSelectSearchParam, ClaimInput,
	getAllTypesOfMetasByPageCode,
	Selector, ValidateStyleAdjustment
} from "@/biz-components/claim-items/components";
import * as CommonDataSource from '@/common-data-source';
import { plus } from '@ey-utils/utils/numberPrecision';
import {useField} from "@formily/react";
import {Field} from "@formily/core/lib/models";
//import {DetailContext} from "@/biz-components/claim-items/components/DetailContext";

/**
 * @author DongPing
 * 2022/1/13 14:23
 *
 * 扣款池财务认领明细
 *
 * */

const PAGE_CODE = 'ClaimInfoA_Deduct_Finance_IT_L';

export function DeductFinance(props: {
	value: any[],
	onChange: (value: any[]) => void,

	// 扣款类型，用于查询扣款明细事项选择框数据
	deductType: string,

	// 认领门店，用于查询柜组
	shop: string,

	/**
	 * 是否显示开票金额
	 * 【开票金额】

		1、是否开票选择是时显示；默认可认领金额，可编辑，认领金额默认可认领金额不可编辑

		2、是否开票选择否时不显示，认领金额可编辑
	 * */
	showInvoiceAmount: boolean
}) {
	const {value = [], onChange, deductType = '', shop = '', showInvoiceAmount = false} = props;
	const [tableColumnMetas, setTableColumnMetas] = useState<any[]>([]);
	useEffect(function () {
		getAllTypesOfMetasByPageCode(PAGE_CODE).then((result) => {
			setTableColumnMetas(result.tableColumnMetas);
		})
	}, []);
	//const detailMode = useContext(DetailContext);
	// useEffect(function () {
	// 	if(detailMode) return;
	// 	onChange([{claimDescr: ''}])
	// }, []);

	const getLabel = useCallback((key: string) => {
		return tableColumnMetas.find((item) => item.key === key)?.label;
	}, [tableColumnMetas]);


	const querySaleBarCallback = useCallback((p: AsyncPageSelectSearchParam) => {
		return CommonDataSource.shop.queryShopSaleBarsPage(p, shop);
	}, [shop]);
	const querySuppliersCallback = useCallback((p: AsyncPageSelectSearchParam) => {
		return CommonDataSource.shop.queryShopSuppliersPage(p, shop);
	}, [shop]);

	const deductDetailOptions = CommonDataSource.dictionary.useDictionaryChildrenOptions('DCTN_FINC_TYPE', deductType);

	// 供应商必填
	let supplierRequired = false;
	// 删除柜组
	let deleteGZ = false;
	// 删除供应商
	let deleteSupplier = false;


	if(deductType === 'ETC') {
		supplierRequired = true;
		deleteGZ = true;
	} else if(deductType === 'YH') {
		deleteSupplier = true;
		deleteGZ = true;
	} else if(deductType === 'GZ') {
		deleteSupplier = true;
		deleteGZ = true;
	}

	const field = useField<Field>();
	useEffect(function () {
		field.setValidator(() => {
			let suppliersValid = (value || []).every((item) => {

				if(deleteSupplier) {
					return true;
				} else {
					return !!item.supplierCode
				}
			});

			// 本次认领金额校验
			let thisAmtValid = (value || []).every((item) => !!item.thisClaimAmt);

			// 开票金额校验
			let invoiceValid = (value || []).every((item) => {
				if(!showInvoiceAmount) return true;
				// 开票金额没填
				//if(!item.invcAmt && (item.invcAmt!==0)) return true;
				let nThisAmt = Number(item.thisClaimAmt);
				let nInvoice = Number(item.invcAmt);
				if(isNaN(nThisAmt) || isNaN(nInvoice)) return false;
				if(nInvoice <= 0) {
					return false;
				}
				return nInvoice <= nThisAmt;
			});

			if(supplierRequired && !suppliersValid) {
				return {type: 'error', message: '认领信息填写有误'}
			} else if(!thisAmtValid) {
				return {type: 'error', message: '认领信息填写有误'}
			} else if(!invoiceValid) {
				return {type: 'error', message: '开票金额必须小于等于本次认领金额，且大于0'}
			} else {
				return null;
			}
		})
	}, [field, supplierRequired, value, deleteSupplier, showInvoiceAmount]);

	return (
		<Table scroll={{x: 'max-content'}} size={"small"} pagination={false} dataSource={value}>
			<Table.Column fixed title={formatMessage({ id: 'config.common.label.seq' })} render={(t, r: any, index) => index + 1}/>

			<Table.Column dataIndex={'dctnDetail'} title={getLabel('dctnDetail')} render={(t, r: any) => {
				return (
					<ValidateStyleAdjustment invalid={false}>
						<Selector
							value={t}
							onChange={(v) => {
								r.dctnDetail = v;
								onChange([...value])
							}}
							dataSource={deductDetailOptions}/>
					</ValidateStyleAdjustment>

				)
			}}/>

			{
				!deleteSupplier &&
					<>
						<Table.Column dataIndex={'supplierCode'} title={getLabel('supplierCode')} render={(t, r: any) => {
							return (
								<ValidateStyleAdjustment invalid={supplierRequired && !t}>
									<AsyncPageSelect
										valueAsSelectResult
										value={t}
										onChange={(v, name) => {
											r.supplierCode = v;
											r.supplierName = name;
											onChange([...value])
										}}
										search={querySuppliersCallback}/>
								</ValidateStyleAdjustment>
							)
						}}/>
						<Table.Column dataIndex={"supplierName"} title={getLabel("supplierName")}/>
					</>
			}

			<Table.Column dataIndex={'thisClaimAmt'} title={getLabel('thisClaimAmt')} render={(t, r: any) => {
				return (
					<ValidateStyleAdjustment invalid={!t}>
					<ClaimInput

						type={"number"}
						value={t}
						onChange={(e) => {
							if(/^-/.test(e.target.value)) return;
							r.thisClaimAmt = Number(e.target.value);
							onChange([...value])
						}}
						/>
					</ValidateStyleAdjustment>
				)
			}}/>
			{
				showInvoiceAmount &&
				<Table.Column dataIndex={'invcAmt'} title={getLabel('invcAmt')} render={(t, r: any) => {
					return (
						<ValidateStyleAdjustment invalid={false}>
						<ClaimInput
							type={"number"}
							value={t}
							onChange={(e) => {
								r.invcAmt = Number(e.target.value);
								onChange([...value])
							}}
						/>
						</ValidateStyleAdjustment>
					)
				}}/>
			}
			<Table.Column dataIndex={'claimDescr'} title={getLabel('claimDescr')} render={(t, r: any) => {
				return (
					<ValidateStyleAdjustment invalid={false}>
						<ClaimInput
							value={t}
							onChange={(e) => {
								r.claimDescr = e.target.value;
								onChange([...value])
							}}
						/>
					</ValidateStyleAdjustment>
				)
			}}/>

			{
				deleteGZ ? null :
					<>
						<Table.Column dataIndex={'branchDeptCode'} title={getLabel('branchDeptCode')} render={(t, r: any) => {
							return (
								<ValidateStyleAdjustment invalid={false}>
									<AsyncPageSelect
										valueAsSelectResult
										value={t}
										onChange={(v, name) => {
											r.branchDeptCode = v;
											r.branchDeptName = name;
											onChange([...value])
										}}
										search={querySaleBarCallback}/>
								</ValidateStyleAdjustment>
							)
						}}/>
						<Table.Column dataIndex={'branchDeptName'} title={getLabel('branchDeptName')}/>
					</>

			}


		</Table>
	)
}

DeductFinance.calcTotalAmount = calcTotalAmount;

/**
 * 计算明细项的金额汇总
 * */
function calcTotalAmount(data: any[] = []): number {
	let result = 0;
	try {
		for(const item of data) {
			let n = Number(item?.thisClaimAmt);
			if(!isNaN(n)) {
				result = plus(result, n);
			}
		}
		return result;	
	} catch (error) {
		
	}
}
